package com.hhxy.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 解决中文乱码
 * @author ghp
 * @date 2022/9/13
 */
@WebServlet("/chineseServlet")
public class ChineseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String data = "张三";

        //方式一：
        //设置IDEA对响应数据的编码格式（因为再IDEA中默认是使用UTF-8，所以这里可以省略，但是写上可以提高容错）
        response.setCharacterEncoding("utf-8");
        //设置浏览器对Servlet的数据编码格式（Google浏览器默认是采用iso-8859-1解码格式）
        response.setHeader("Content-Type","text/html;charset=utf-8");

        /*----------------------------------------------------------------------------------*/

        //方式二（推荐使用）：设置IDEA对响应数据的编码格式，同时设置浏览器对响应数据的解码格式
//        response.setContentType("text/html;charset=utf-8");

        PrintWriter pw = response.getWriter();
        pw.write(data);
    }
}